import tinymce from 'tinymce/tinymce'
import store from '@/store'
import { checkBeforeInsert, getSelectionNode, getPageSheetNode } from '@/utils/helpers'
import { contentTypes } from '@/constants/structure'
// import { v4 as uuid } from 'uuid'

// 设置的选项
const entries = {
  一级条标题: 'item1',
  二级条标题: 'item2',
  三级条标题: 'item3',
  四级条标题: 'item4'
}

tinymce.PluginManager.add('chapter', function (editor) {
  editor.on('keyup', (event) => {
    const node = getSelectionNode(editor)
    if (node?.classList?.contains('list-title')) {
      if (event.key === 'Delete' || event.key === 'Backspace') {
        store.commit('xmleditor/UPDATE_DOC_STRUCTURE')
      }
    }
  })

  const arr = Object.keys(entries).map((item) => {
    return {
      type: 'togglemenuitem',
      text: item,
      onAction: () => {
        const currentNode = getSelectionNode(editor)
        // 2 如果就是当前的层级，则取消题条
        if (currentNode?.dataset?.type === entries[item]) {
          editor.dom.setAttrib(currentNode, 'data-type', 'paragraph')
          editor.dom.removeClass(currentNode, 'list-title');
          editor.dom.setHTML(currentNode, currentNode.innerText)
        } else {
          // 3 设置为对应题条
          editor.dom.setAttrib(currentNode, 'data-type', entries[item])
          editor.dom.addClass(currentNode, 'list-title');
          // 只在中英文情况下设置
          store.getters.languageType === 'both' && editor.dom.setHTML(currentNode, `${currentNode.innerText}&#8203;`);
          store.commit('xmleditor/ADD_NEW_PAGE_EDITABLE', currentNode?.dataset?.blockId)
        }

        const currentPage = getPageSheetNode(editor)
        // 更改题条编号
        store.commit('xmleditor/UPDATE_DOC_STRUCTURE')
        // 如果是术语页面
        if (currentPage?.dataset?.contentPageType=== 'terms_definitions') {
          editor.fire('termsUpdated')
        }
      },
      onSetup: function (e) {
        const currentNode = getSelectionNode(editor)
        const currentPage = getPageSheetNode(editor)
        // 章节的段落不能修改层级
        if (contentTypes.includes(currentNode?.dataset?.type) || !checkBeforeInsert('item', true)) {
          e.setDisabled(true)
        }
        // 如果在公式表格图片内，不能设置题条
        const disabledParent = editor.dom.getParent(currentNode, 'table,div[data-type="formula"],div[data-type="figure"],p.item_list')
        if (disabledParent) {
          return e.setDisabled(true)
        }
        // 只有paragraph和item1~item4才可以设置标题
        const isSettable = editor.dom.is(currentNode, 'p[data-type="paragraph"],p[data-type^="item"]')
        if (!isSettable) {
          return e.setDisabled(true)
        }

        // 如果是前言页，不能设置条
        if (currentPage?.dataset?.pageType === 'foreword') {
          return e.setDisabled(true)
        }

        // 如果是【范围】中的内容，不能设置条
        if (currentPage?.dataset?.contentPageType === 'scope') {
          return e.setDisabled(true)
        }

        // 1 设置当前节点题条等级为选中状态
        e.setActive(currentNode?.dataset?.type === entries[item])

        // 如果是引言页，只能设置标题一
        if (currentPage?.dataset?.pageType === 'introduction') {
          return e.setDisabled(entries[item] === 'item2' || entries[item] === 'item3' || entries[item] === 'item4')
        }
        // 4 跳级设置禁用并给提示，如 2.1 下直接设置 2.1.1.1
        const prevItemType = getPrevListTitle(currentNode)?.dataset?.type

        // 附录页
        if (currentPage?.dataset?.pageType === 'annex') {
          // 附录页顶部的三行标题不能设置
          const isAnnexNumber = editor.dom.is(currentNode, '[data-annex-number]')
          const isAnnexType = editor.dom.is(currentNode, '[data-annex-type]')
          const isAnnexTitle = editor.dom.is(currentNode, '[data-annex-title]')
          if (isAnnexNumber || isAnnexType || isAnnexTitle) {
            return e.setDisabled(true)
          }

          // 如果没有设置item1,不能设置item2和item3
          if (!prevItemType) {
            return e.setDisabled(entries[item] === 'item2' || entries[item] === 'item3' || entries[item] === 'item4')
          }
          // 条1下面不能设置：条3
          if (prevItemType === 'item1') {
            return e.setDisabled(entries[item] === 'item3' || entries[item] === 'item4')
          }

          // 如果在附录页不能设置标题4，最多只能设置标题3
          return e.setDisabled(entries[item] === 'item4')
        }
        // 4.1 章下面不能设置：条2/3/4
        if (contentTypes.includes(prevItemType)) {
          e.setDisabled(entries[item] === 'item2' || entries[item] === 'item3' || entries[item] === 'item4')
        }
        // 4.2 条1下面不能设置：条3/4
        if (prevItemType === 'item1') {
          e.setDisabled(entries[item] === 'item3' || entries[item] === 'item4')
        }
        // 4.3 条2下面不能设置：条4
        if (prevItemType === 'item2') {
          e.setDisabled(entries[item] === 'item4')
        }
      }
    }
  })
  return (
    editor.ui.registry.addMenuButton('chapter', {
      tooltip: '题条',
      icon: 'unordered-list',
      fetch: (cb) => cb(arr)
    }),
    {
      getMetadata: function () {
        return {
          name: '题条',
          url: 'http://sfrj.cn'
        }
      }
    }
  )
})

/** 查找最近的章节、题条等级，包括 chapter 和 item1-item4 */
function getPrevListTitle(node) {
  const { getPrev, is} = tinymce.activeEditor.dom
  if (!node) {
    console.warn('获取前一个章节或标题')
    return null
  }
  const prev = getPrev(node, '.list-title')
  if (prev && prev !== node) {
    return prev
  }
  if (is(node, '[data-page-type="content"]')) {
    const titleNodes = [... node.querySelectorAll('.list-title')]
    if (titleNodes.length) {
      return titleNodes[titleNodes.length - 1]
    }
    return getPrevListTitle(getPrev(node, '[data-page-type="content"]'))
  }
  const parent = node.parentNode
  // 如果父元素到外层
  if (is(parent, '[data-page-type="content"]')){
    return getPrevListTitle(getPrev(parent, '[data-page-type="content"]'))
  } else {
    return getPrevListTitle(parent)
  }
}
